package com.aspirecn.auth.config;

import com.aspirecn.auth.config.security.CustomClientCredentialsTokenEndpointFilter;
import com.aspirecn.auth.config.security.MyAuthenticationProvider;
import com.aspirecn.auth.service.DomainUserDetailsService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(OAuth2SecurityConfiguration.class);

    @Bean
    public UserDetailsService userDetailsService(){
        return new DomainUserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService())
//            .passwordEncoder(passwordEncoder());
//    }
	//配置使用自定义登陆验证类
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 将验证过程交给自定义验证工具
		final MyAuthenticationProvider provider = new MyAuthenticationProvider(userDetailsService());
		auth.authenticationProvider(provider);
	}
    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }

    //不定义没有password grant_type
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
		http
		.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
		.anonymous().disable()
	  	.authorizeRequests()
	  	.anyRequest().authenticated();
    }    

    
	@Bean
	ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() {
		final ClientCredentialsTokenEndpointFilter tokenEndpointFilter = new CustomClientCredentialsTokenEndpointFilter();
		try {
			tokenEndpointFilter.setAuthenticationEntryPoint(oAuth2AuthenticationEntryPoint());
			tokenEndpointFilter.setAuthenticationManager(authenticationManagerBean());
			tokenEndpointFilter.setFilterProcessesUrl("/oauth/token");
			return tokenEndpointFilter;
		} catch (final Exception e) {
			throw new IllegalStateException(e);
		}
	}

	@Bean
	OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint() {
		final OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
		entryPoint.setRealmName("oauth/client");
		entryPoint.setTypeName("Basic");
		//自定义错误异常响应
		//entryPoint.setExceptionRenderer(exceptionRenderer);
		//自定义错误异常响应
		entryPoint.setExceptionTranslator(webResponseExceptionTranslator());
		return entryPoint;
	}
	
	//自定义错误异常响应包体
	@Bean
	public WebResponseExceptionTranslator webResponseExceptionTranslator() {
		return new DefaultWebResponseExceptionTranslator() {
			@Override
			public ResponseEntity translate(Exception e) throws Exception {
				LOG.info("-------------- WebResponseExceptionTranslator");
				ResponseEntity responseEntity = super.translate(e);
				OAuth2Exception body = (OAuth2Exception) responseEntity.getBody();
				return responseEntity;
			}
		};
	}
}
